package com.gusha.utils;

import java.beans.PropertyDescriptor;
import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.BeansException;

/** 
 * @Description: 用来动态更新，实体属性为Null时不更新
 * @author: 龙爷
 * @date: 2017-12-22 09:10
 */
public class UpdateUtil extends BeanUtils{

	/**
     * 将不为空值的属性从目标实体类中复制到源实体类中
     */
    public static void copyNonNullProperties(Object src,Object target) throws BeansException{
        BeanUtils.copyProperties(target,src,getNullProperties(src));
    }

    /**
     * 将不为空的properties给找出来,然后返回出来
     * @param src
     * @return
     */
    private static String[] getNullProperties(Object src){
        BeanWrapper srcBean = new BeanWrapperImpl(src);
        PropertyDescriptor[] pds = srcBean.getPropertyDescriptors();
        Set<String> emptyName = new HashSet<>();
        for(PropertyDescriptor p:pds){
            Object srcValue = srcBean.getPropertyValue(p.getName());
            if(srcValue != null) emptyName.add(p.getName());
        }
        String[] result = new String[emptyName.size()];
        return emptyName.toArray(result);
    }
}
